package com.qk.management.aop.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.qk.entity.OperateLog;
import com.qk.management.service.OperateLogService;
import com.qk.utils.CurrentUserContextHolders;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 *
 * @author lyl
 * @created 2025/10/17 20:13
 * @description
 *
 */
@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class LogRecordAspect {

    @Autowired
    private OperateLogService operateLogService;
    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt() {
    }

    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        log.info("开始记录日志");
        Integer operateUserId = null;
        String className = null;
        String methodName = null;
        String methodParams = null;
        Object returnValue = null;
        long startTime = 0;
        long endTime = 0;
        OperateLog op = null;
        String error = null;
        try{
            operateUserId = CurrentUserContextHolders.get();
            className = pjp.getTarget().getClass().getName();
            methodName = pjp.getSignature().getName();
            methodParams = Arrays.toString(pjp.getArgs());

            startTime = System.currentTimeMillis();
            returnValue = pjp.proceed();
        }catch (Exception e){
            log.error("业务失败：{}", e.getMessage());
            error =  String.format("业务操作失败%s", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }finally {
            endTime = System.currentTimeMillis();
            op = OperateLog.builder()
                    .operateUserId(operateUserId)
                    .className(className)
                    .methodName(methodName)
                    .methodParams(methodParams)
                    .costTime(endTime - startTime)
                    .operateTime(LocalDateTime.now())
                    .returnValue(ObjectUtil.isNotNull(returnValue) ? returnValue.toString() : error)
                    .build();
            try {
                operateLogService.addLog(op);
            }catch (Exception e){
                log.error("记录日志失败：{}", e.getMessage());
            }
        }
        return returnValue;

    }
}
